//
//  ReservacionesDetail.m
//  Futbol5Final
//
//  Created by Ulises Ocana on 4/14/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "ReservacionesDetail.h"
#import "HoraCell.h"
#import "ReservacionVO.h"

@implementation ReservacionesDetail

@synthesize fecha,tabla,reservaciones,cancha;


-(id) initWithDate:(NSDate *) date:(NSArray *)reservacionesp:(CanchaVO *)canchap{
    
     self = [[[ReservacionesDetail alloc] initWithNibName:@"ReservacionesDetail" bundle:nil] autorelease];
    
    NSDateFormatter* formatter = [[[NSDateFormatter alloc] init] autorelease];
    
    //Set the required date format
    
    [formatter setDateFormat:@"yyyy-MM-dd"];
    
    //Get the string date
    
    NSString* str = [formatter stringFromDate:date];
    
    dateFromCalendar = str;
    
    horas = [[NSArray alloc]initWithObjects:@"6",@"7",@"8",@"9",@"10",@"11",@"12",@"13","14",@"15",@"16",@"17",@"18",@"19",@"20",@"21",@"22",@"23", nil];        
    
    reservaciones = reservacionesp;
    
    cancha = canchap;
    
    return self;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
    }
    return self;
}



- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 18;
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"horas";
    
    UIImage *image = [UIImage imageNamed:@"boton_reservar.gif"]; 
    
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
    
    NSString *nombre = [NSString stringWithFormat:@"%@:00",[horas objectAtIndex:indexPath.row]];
    

       UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        
        if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
            
            if(![self checkIdReservado:indexPath.row]){
                cell.accessoryView = imageView;                
            }else{
                cell.accessoryType = UITableViewCellAccessoryNone;
            }
 
            cell.textLabel.text = nombre;
        }
    
    
    
    nombre = nil;
    return cell;
}

-(BOOL) checkIdReservado:(int) indice{
    
    BOOL esta = false;
    
    ReservacionVO *reserTmp;
    
    NSEnumerator *arrenum = [reservaciones objectEnumerator];
    id cobj;   
    
    while ( cobj = [arrenum nextObject] ) {  
        reserTmp = cobj;
        
        if(reserTmp.horaInicio == [[horas objectAtIndex:indice]intValue]){
            return true;
        }
        
    }
    
    return esta;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    selectedIndex = indexPath.row;
    
    tabla = tableView;
    
    if(![self checkIdReservado:indexPath.row]){
        alertWithYesNoButtons = [[UIAlertView alloc] initWithTitle:@"Confirmacion de Reservacion"
                                                           message:@"Esta seguro que desea reservar?" delegate:self cancelButtonTitle:@"No" otherButtonTitles:@"Si", nil];
        
        [alertWithYesNoButtons show];
        [alertWithYesNoButtons release];                
    }    
    
}


- (void)alertView : (UIAlertView *)alertView clickedButtonAtIndex : (NSInteger)buttonIndex
{
    if(alertView == alertWithYesNoButtons)
    {
        if(buttonIndex == 1)
        {
            
            NSString *url = [NSString stringWithFormat:@"http://localhost:8080/futbol/reservacion/add/johan/1/89456456/%@/%d/CC/%d/%@",[horas objectAtIndex:selectedIndex],[[horas objectAtIndex:selectedIndex]intValue]+1,cancha.idCancha,dateFromCalendar];
            
            responseData = [[NSMutableData data] retain];
            NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
            [[NSURLConnection alloc] initWithRequest:request delegate:self];
            
        }
    }
}



- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
	[responseData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
	[responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
	//label.text = [NSString stringWithFormat:@"Connection failed: %@", [error description]];
    NSLog(@"error %@",[error description]);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
	[connection release];
    
	NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
	[responseData release];
    
    [self.view reloadInputViews];
    
    tabla = [self.view.subviews objectAtIndex:1];
    
    ReservacionVO *reservacionVoTmp;
    
    reservacionVoTmp = [[ReservacionVO alloc]initWithData:0 :[[horas objectAtIndex:selectedIndex]intValue] :1 :1 :1 :@"12/12/12"];           
    
    [reservaciones addObject:reservacionVoTmp];
    
    [tabla reloadData];
	
}


- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.tabla.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    
    fecha.text = dateFromCalendar;
    

}


-(void) viewWillAppear:(BOOL)animated{
    [super viewWillAppear:true];
    [tabla reloadData];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
